const express = require('express');
const router = express.Router();
const db = require('../db');

// 获取排班结果
router.get('/', (req, res) => {
  const { shift_type_id, start, end, start_date, end_date, employee_id } = req.query;
  // 优先使用start和end参数，兼容旧的start_date和end_date参数
  const actualStart = start || start_date;
  const actualEnd = end || end_date;

  let sql = `SELECT s.*, st.name as shift_type_name, e.name as employee_name, e.type as employee_type FROM schedules s
             LEFT JOIN shift_types st ON s.shift_type_id = st.id
             LEFT JOIN employees e ON s.employee_id = e.id`;
  const params = [];
  const conditions = [];

  if (employee_id) {
    conditions.push(`s.employee_id = ?`);
    params.push(employee_id);
  }
  if (shift_type_id) {
    conditions.push(`s.shift_type_id = ?`);
    params.push(shift_type_id);
  }
  if (actualStart && actualEnd) {
    conditions.push(`s.schedule_date BETWEEN ? AND ?`);
    params.push(actualStart, actualEnd);
  } else if (actualStart) {
    conditions.push(`s.schedule_date >= ?`);
    params.push(actualStart);
  } else if (actualEnd) {
    conditions.push(`s.schedule_date <= ?`);
    params.push(actualEnd);
  }

  if (conditions.length > 0) {
    sql += ' WHERE ' + conditions.join(' AND ');
  }

  sql += ' ORDER BY s.schedule_date, e.type ASC, e.name';

  db.all(sql, params, (err, rows) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json(rows);
  });
});

// 获取单个排班记录
router.get('/:id', (req, res) => {
  const id = req.params.id;
  const sql = `SELECT s.*, st.name as shift_type_name, e.name as employee_name FROM schedules s
               LEFT JOIN shift_types st ON s.shift_type_id = st.id
               LEFT JOIN employees e ON s.employee_id = e.id
               WHERE s.id = ?`;

  db.get(sql, [id], (err, row) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    if (!row) {
      res.status(404).json({ message: '排班记录不存在' });
      return;
    }
    res.json(row);
  });
});

// 创建排班记录
router.post('/', (req, res) => {
  const { shift_type_id, employee_id, schedule_date } = req.body;
  const sql = `INSERT INTO schedules (shift_type_id, employee_id, schedule_date)
               VALUES (?, ?, ?)`;

  db.run(sql, [shift_type_id, employee_id, schedule_date], function(err) {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.status(201).json({
      id: this.lastID,
      message: '排班记录创建成功',
      data: { id: this.lastID, shift_type_id, employee_id, schedule_date }
    });
  });
});

// 更新排班记录
router.put('/:id', (req, res) => {
  const id = req.params.id;
  const { shift_type_id, employee_id, schedule_date } = req.body;
  const sql = `UPDATE schedules SET shift_type_id = ?, employee_id = ?,
               schedule_date = ? WHERE id = ?`;

  db.run(sql, [shift_type_id, employee_id, schedule_date, id], function(err) {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    if (this.changes === 0) {
      res.status(404).json({ message: '排班记录不存在' });
      return;
    }
    res.json({ message: '排班记录更新成功' });
  });
});

// 删除排班记录
router.delete('/:id', (req, res) => {
  const id = req.params.id;
  db.run('DELETE FROM schedules WHERE id = ?', [id], function(err) {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    if (this.changes === 0) {
      res.status(404).json({ message: '排班记录不存在' });
      return;
    }
    res.json({ message: '排班记录删除成功' });
  });
});

// 生成排班
router.post('/generate', (req, res) => {
  const { shift_type_id, start_date, end_date, first_employee_id } = req.body;

  // 验证参数
  if (!shift_type_id || !start_date || !end_date) {
    return res.status(400).json({ error: '排班类型ID、开始日期和结束日期为必填项' });
  }

  // 检查日期有效性
  if (new Date(start_date) > new Date(end_date)) {
    return res.status(400).json({ error: '开始日期不能晚于结束日期' });
  }

  // 获取排班类型配置
  db.get('SELECT * FROM shift_types WHERE id = ?', [shift_type_id], (err, shiftType) => {
    if (err) {
      return res.status(500).json({ error: err.message });
    }
    if (!shiftType) {
      return res.status(404).json({ message: '排班类型不存在' });
    }

    // 获取适用人员
    db.all('SELECT * FROM employees WHERE type = ? ORDER BY serial_number', [shiftType.applicable_type], (err, employees) => {
      if (err) {
        return res.status(500).json({ error: err.message });
      }
      if (employees.length === 0) {
        return res.status(400).json({ message: '没有符合条件的人员' });
      }

      // 获取节假日
      db.all('SELECT date FROM holidays WHERE date BETWEEN ? AND ? AND type = 1', [start_date, end_date], (err, holidays) => {
        if (err) {
          return res.status(500).json({ error: err.message });
        }
        const holidaySet = new Set(holidays.map(h => h.date));

        // 获取调休日
        db.all('SELECT date FROM holidays WHERE date BETWEEN ? AND ? AND type = 2', [start_date, end_date], (err, adjustWorkDays) => {
          if (err) {
            return res.status(500).json({ error: err.message });
          }
          const adjustWorkDaySet = new Set(adjustWorkDays.map(h => h.date));

          // 生成日期范围内的排班
          const start = new Date(start_date);
          const end = new Date(end_date);
          let currentEmployeeIndex = 0;
          
          if (first_employee_id) {
            // 查找first_employee_id在员工列表中的索引
            const firstEmployeeIndex = employees.findIndex(emp => emp.id === first_employee_id);
            if (firstEmployeeIndex !== -1) {
              currentEmployeeIndex = firstEmployeeIndex;
            }
          }

          // 事务处理排班生成与删除
          db.run('BEGIN TRANSACTION', (err) => {
            if (err) {
              return res.status(500).json({ error: err.message });
            }

            // 清空现有排班
            db.run('DELETE FROM schedules WHERE shift_type_id = ? AND schedule_date BETWEEN ? AND ?',
            [shift_type_id, start_date, end_date], function(err) {
              if (err) {
                db.run('ROLLBACK');
                return res.status(500).json({ error: err.message });
              }

              try {
                const stmt = db.prepare('INSERT OR IGNORE INTO schedules (shift_type_id, employee_id, schedule_date) VALUES (?, ?, ?)');
                let date = new Date(start);
                let generatedCount = 0;
                const employeeCount = employees.length;

                while (date <= end) {
                  const dateStr = date.toISOString().split('T')[0];
                  const dayOfWeek = date.getDay(); // 0-6, 0是星期日
                  const bitmask = 1 << (dayOfWeek === 0 ? 6 : dayOfWeek - 1); // 转换为周一到周日的位掩码

                  // 检查是否是节假日或调休日（优先级最高）
                  let shouldSchedule = false;
                  if (holidaySet.has(dateStr)) {
                    // 如果是节假日且设置节假日排班，则直接排班
                    shouldSchedule = shiftType.holiday_work_schedule;
                  } else if (adjustWorkDaySet.has(dateStr)) {
                    // 如果是调休日且设置调休日排班，则直接排班
                    shouldSchedule = shiftType.adjust_work_day_schedule;
                  } else {
                    // 非节假日和非调休日，检查是否在循环配置中
                    shouldSchedule = (shiftType.cycle & bitmask) !== 0;
                  }

                  // 如果不应该排班，则继续下一天
                  if (!shouldSchedule) {
                    date.setDate(date.getDate() + 1);
                    continue;
                  }

                  // 分配人员
                  const employee = employees[currentEmployeeIndex];
                  
                  // 插入记录
                  stmt.run(shift_type_id, employee.id, dateStr);
                  generatedCount++;

                  // 更新下一个人员索引
                  currentEmployeeIndex = (currentEmployeeIndex + 1) % employeeCount;

                  date.setDate(date.getDate() + 1);
                }

                stmt.finalize((err) => {
                  if (err) {
                    db.run('ROLLBACK');
                    return res.status(500).json({ error: err.message });
                  }
                  db.run('COMMIT', (err) => {
                    if (err) {
                      db.run('ROLLBACK');
                      return res.status(500).json({ error: err.message });
                    }
                    res.json({
                      message: `排班生成成功，共生成 ${generatedCount} 条记录`,
                      generated_count: generatedCount
                    });
                  });
                });
              } catch (error) {
                db.run('ROLLBACK');
                return res.status(500).json({ error: error.message });
              }
            });
          });
        });
      });
    });
  });
});

// 根据员工ID和月份获取排班
router.get('/getByEmployeeAndMonth/:employeeId/:year/:month', (req, res) => {
  const { employeeId, year, month } = req.params;
  // 计算月份的第一天和最后一天
  const startDate = `${year}-${String(month).padStart(2, '0')}-01`;
  const endDate = new Date(year, month, 0).toISOString().split('T')[0];

  const sql = `SELECT s.*, st.name as shift_type_name FROM schedules s
               LEFT JOIN shift_types st ON s.shift_type_id = st.id
               WHERE s.employee_id = ? AND s.schedule_date BETWEEN ? AND ?
               ORDER BY s.schedule_date`;

  db.all(sql, [employeeId, startDate, endDate], (err, rows) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json({ data: rows });
  });
});

// 换班操作
router.post('/swapShifts', (req, res) => {
  const { scheduleId1, scheduleId2 } = req.body;

  // 开始事务
  db.serialize(() => {
    db.run('BEGIN TRANSACTION');

    // 获取第一个排班记录
    db.get('SELECT * FROM schedules WHERE id = ?', [scheduleId1], (err1, schedule1) => {
      if (err1) {
        db.run('ROLLBACK');
        res.status(500).json({ error: err1.message });
        return;
      }

      if (!schedule1) {
        db.run('ROLLBACK');
        res.status(404).json({ message: '第一个排班记录不存在' });
        return;
      }

      // 获取第二个排班记录
      db.get('SELECT * FROM schedules WHERE id = ?', [scheduleId2], (err2, schedule2) => {
        if (err2) {
          db.run('ROLLBACK');
          res.status(500).json({ error: err2.message });
          return;
        }

        if (!schedule2) {
          db.run('ROLLBACK');
          res.status(404).json({ message: '第二个排班记录不存在' });
          return;
        }

        // 交换两个排班记录的员工ID
        db.run('UPDATE schedules SET employee_id = ? WHERE id = ?', [schedule2.employee_id, scheduleId1], (err3) => {
          if (err3) {
            db.run('ROLLBACK');
            res.status(500).json({ error: err3.message });
            return;
          }

          db.run('UPDATE schedules SET employee_id = ? WHERE id = ?', [schedule1.employee_id, scheduleId2], (err4) => {
            if (err4) {
              db.run('ROLLBACK');
              res.status(500).json({ error: err4.message });
              return;
            }

            // 提交事务
            db.run('COMMIT', (err5) => {
              if (err5) {
                res.status(500).json({ error: err5.message });
                return;
              }

              res.json({ message: '换班成功' });
            });
          });
        });
      });
    });
  });
});

module.exports = router;
